import { useNavigate } from "react-router-dom";
import { useState } from "react";
import { Form, Input, Button, message } from "antd";
import request from "../utils/request";
import { useMenu } from "../context/MenuContext";
import { useAuth } from "../context/AuthContext";


// 登录成功后，将 authToken 存储到 Cookie（HttpOnly + Secure + SameSite）
// function setAuthTokenCookie(token) {
//   document.cookie = `authToken=${token}; SameSite=Lax; Max-Age=3600; Path=/`;
// }


export default function Login() {
  const [showRegister, setShowRegister] = useState(false);
  const [regMsg, setRegMsg] = useState("");
  const navigate = useNavigate();

  // 菜单
  const { setMenus } = useMenu();
  // 权限按钮
  const { setAuthButtons } = useAuth();

  const apiBase = import.meta.env.VITE_API_BASE;
// 用于 axios 或 fetch 请求
  console.log("API Base URL:", apiBase);

  // 登录
  const onFinishLogin = async (values) => {
    const { user, pwd } = values;
    // 这里实际需要后端API接口校验用户名和密码
    const loginRes = await request.post(apiBase+"/login", {
      username: user,
      password: pwd
    });

    if (loginRes.data && loginRes.data.code === 200) {

      console.log("登录成功", loginRes.data);
      localStorage.setItem("isLoggedIn", true);
      // 模拟设置 token 到 Cookie 
      console.log("token:", loginRes.data.data.token);
      // 设置 authToken Cookie
      // setAuthTokenCookie(loginRes.data.data.token);

      // 登录成功后请求菜单
      const res = await request.get(apiBase+"/user/authTree");
      if (res.data && res.data.code === 200) {
        localStorage.setItem("menus", JSON.stringify(res.data.data));
        setMenus(res.data.data);
      }
      // 请求按钮权限
      const btnRes = await request.get(apiBase+"/user/authButton");
      if (btnRes.data && btnRes.data.code === 200) {
        localStorage.setItem("authButtons", JSON.stringify(btnRes.data.data));
        // 更新权限按钮状态
        setAuthButtons(btnRes.data.data);
      }
      // 登录成功后跳转到首页
      message.success("登录成功");
      navigate("/");

    } else {
      // 登录失败
      message.error("用户名或密码错误");
      return;
    }

    // if (user === "admin" && pwd === "123456") {
    //   // 模authTree拟登录成功，设置 token 到 localStorage
    //   // localStorage.setItem("token", "mock-token");

    // } else {
    //   message.error("用户名或密码错误");
    // }
  };

  // 注册
  const onFinishRegister = (values) => {
    const { regUser, regEmail, regPwd, regPwd2 } = values;
    if (!regUser || !regEmail || !regPwd || !regPwd2) {
      setRegMsg("请填写所有注册信息");
      return;
    }
    if (regPwd !== regPwd2) {
      setRegMsg("两次输入的密码不一致");
      return;
    }
    setRegMsg("已提交注册信息，请等待邮件通知");
  };

  return (
    <div style={{
      minHeight: "100vh",
      display: "flex",
      alignItems: "center",
      justifyContent: "center",
      background: "#f5f5f5"
    }}>
      {!showRegister ? (
        <Form
          onFinish={onFinishLogin}
          style={{ width: 340, background: "#fff", padding: 32, borderRadius: 8, boxShadow: "0 2px 8px #0001" }}
        >
          <h2 style={{ textAlign: "center" }}>登录</h2>
          <Form.Item name="user" rules={[{ required: true, message: "请输入用户名" }]}>
            <Input placeholder="用户名" />
          </Form.Item>
          <Form.Item name="pwd" rules={[{ required: true, message: "请输入密码" }]}>
            <Input.Password placeholder="密码" />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" block>登录</Button>
          </Form.Item>
          <Form.Item>
            <Button block onClick={() => setShowRegister(true)}>注册</Button>
          </Form.Item>
        </Form>
      ) : (
        <Form
          onFinish={onFinishRegister}
          style={{ width: 360, background: "#fff", padding: 32, borderRadius: 8, boxShadow: "0 2px 8px #0001" }}
        >
          <h2 style={{ textAlign: "center" }}>注册</h2>
          <Form.Item name="regUser" rules={[{ required: true, message: "请输入用户名" }]}>
            <Input placeholder="用户名" />
          </Form.Item>
          <Form.Item name="regEmail" rules={[{ required: true, message: "请输入邮箱" }]}>
            <Input placeholder="邮箱" />
          </Form.Item>
          <Form.Item name="regPwd" rules={[{ required: true, message: "请输入密码" }]}>
            <Input.Password placeholder="密码" />
          </Form.Item>
          <Form.Item name="regPwd2" rules={[{ required: true, message: "请确认密码" }]}>
            <Input.Password placeholder="确认密码" />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" block>提交注册</Button>
          </Form.Item>
          <Form.Item>
            <Button block onClick={() => { setShowRegister(false); setRegMsg(""); }}>返回登录</Button>
          </Form.Item>
          {regMsg && <div style={{ color: regMsg.startsWith("已提交") ? "green" : "red", marginTop: 12, textAlign: "center" }}>{regMsg}</div>}
        </Form>
      )}
    </div>
  );
}